<template>
  <div class="card-header">30天用水趋势</div>
  <div style="flex: 1" v-loading="loading">
    <BaseChart :responsive="true" v-if="!loading" :options="chartOption" />
  </div>
</template>

<script setup>
import { getMetersReportApi } from "@/api/meter";
import { useCompanyStore } from "@/stores/company";
import { useMeterStore } from "@/stores/meter";
import dayjs from "dayjs";
import { watch, ref } from "vue";
import { handleError } from "@/utils/handleError";

let meterStore = useMeterStore();
let loading = ref(false);
let companyStore = useCompanyStore();
let firstLevelData = ref([]);
let secondLevelData = ref([]);
let chartOption = ref({
  xAxisData: [],
  yAxisUnit: "m³",
  series: [
    {
      name: "二级表",
      data: [],
      type: "line",
    },
    {
      name: "一级表",
      data: [],
      type: "line",
    },
  ],
  customColors: ["#8D8D8D", "#409eff"],
});

const time = {
  start_time: dayjs().subtract(30, 'day').startOf('day').valueOf(),
  end_time: dayjs().startOf('day').valueOf(),
  interval: "day",
}

// 使用统一时间配置
async function getFirstLevelData() {
  // 检查一级表数据是否存在
  if (!meterStore.meterLevels || !meterStore.meterLevels[0] || !meterStore.meterLevels[0].length) {
    console.warn('一级表数据不存在');
    return;
  }

  try {
    const res = await getMetersReportApi({
      meters: meterStore.meterLevels[0],
      ...time,
    });

    // 检查返回数据
    if (!res || !res.aggregated_data) {
      console.warn('获取一级表数据返回格式不正确:', res);
      firstLevelData.value = [];
      return;
    }

    firstLevelData.value = res.aggregated_data || [];
  } catch (error) {
    handleError(error, '获取一级表数据失败');
    firstLevelData.value = [];
  }
}

async function getSecondLevelData() {
  // 检查二级表数据是否存在
  if (!meterStore.meterLevels || !meterStore.meterLevels[1] || !meterStore.meterLevels[1].length) {
    console.warn('二级表数据不存在');
    return;
  }


  try {
    const res = await getMetersReportApi({
      meters: meterStore.meterLevels[1],
      ...time
    });

    // 检查返回数据
    if (!res || !res.aggregated_data) {
      console.warn('获取二级表数据返回格式不正确:', res);
      secondLevelData.value = [];
      return;
    }

    secondLevelData.value = res.aggregated_data || [];
  } catch (error) {
    handleError(error, '获取二级表数据失败');
    secondLevelData.value = [];
  }
}

function generateFullMonthData() {
  // 生成最近30天的日期数组（不包含今天）
  const dates = [];
  const labels = [];

  for (let i = 30; i > 0; i--) {
    const date = dayjs().subtract(i, 'day');
    dates.push(date.format('YYYY-MM-DD'));
    labels.push(date.format('MM-DD'));
  }

  return { fullMonthDates: dates, fullMonthLabels: labels };
}

function setChartOption() {
  // 生成完整月份的日期数据
  const { fullMonthDates, fullMonthLabels } = generateFullMonthData();

  // 将一级表数据整理成映射表，方便后续查找
  const firstLevelMap = {};
  if (Array.isArray(firstLevelData.value)) {
    firstLevelData.value.forEach(item => {
      if (item && item.start_time) {
        const dateKey = dayjs(item.start_time).format('YYYY-MM-DD');
        firstLevelMap[dateKey] = Number(item.Value);
      }
    });
  }

  // 将二级表数据整理成映射表，方便后续查找
  const secondLevelMap = {};
  if (Array.isArray(secondLevelData.value)) {
    secondLevelData.value.forEach(item => {
      if (item && item.start_time) {
        const dateKey = dayjs(item.start_time).format('YYYY-MM-DD');
        secondLevelMap[dateKey] = Number(item.Value);
      }
    });
  }

  // 根据完整月份生成数据系列
  const firstLevelValues = fullMonthDates.map(date => {
    const value = firstLevelMap[date];
    return value !== undefined && !isNaN(value) ? +value.toFixed(2) : 0;
  });

  const secondLevelValues = fullMonthDates.map(date => {
    const value = secondLevelMap[date];
    return value !== undefined && !isNaN(value) ? +value.toFixed(2) : 0;
  });

  // 设置图表选项
  chartOption.value = {
    xAxisData: fullMonthLabels,
    yAxisUnit: "m³",
    series: [
      {
        name: "一级表",
        data: firstLevelValues,
        type: "line",
        extra: {
          z: 1000,
        }
      },
      {
        name: "二级表",
        data: secondLevelValues,
        type: "line",
      },

    ],
    hideXAxis: true,
    hideYAxis: true,
    customColors: ["#409eff", "#8D8D8D"],
  };
}

async function fetchData() {
  try {
    loading.value = true;

    // 检查公司信息
    if (!companyStore?.currentCompany?.id) {
      console.warn('当前公司信息不存在');
      loading.value = false;
      return;
    }

    // 确保获取表计列表
    await meterStore.fetchMeterList({
      company_id: companyStore.currentCompany.id,
      type: 1,
    });

    // 并行获取数据
    await Promise.all([
      getFirstLevelData(),
      getSecondLevelData()
    ]);

    setChartOption();
  } catch (error) {
    handleError(error, '获取用水趋势数据失败');
    // 设置空的图表数据
    const { fullMonthLabels } = generateFullMonthData();
    chartOption.value = {
      xAxisData: fullMonthLabels,
      yAxisUnit: "m³",
      series: [
        { name: "一级表", data: Array(fullMonthLabels.length).fill(0), type: "line" },
        { name: "二级表", data: Array(fullMonthLabels.length).fill(0), type: "line" }
      ],
      customColors: ["#8D8D8D", "#409eff"],
    };
  } finally {
    loading.value = false;
  }
}

watch(
  () => companyStore.currentCompany,
  async () => {
    fetchData();
  },
  {
    immediate: true,
  }
);
</script>

<style scoped></style>